const Vue = require("vue");
const VueServerRenderer = require("vue-server-renderer");
const Koa = require("koa");
const Router = require("koa-router");

const fs = require("fs");
const path = require("path");
const chalk = require("chalk");
const static = require("koa-static");

const app = new Koa();
const router = new Router();

const bundle = fs.readFileSync(path.resolve(__dirname, "dist/server.bundle.js"), "utf8");
const template = fs.readFileSync(path.resolve(__dirname, "dist/index.ssr.html"), "utf8");

// 使用服务端打包后的结果
const render = VueServerRenderer.createBundleRenderer(bundle, {
  template,
});

// 优先访问静态目录，然后访问匹配的路由地址
app.use(static(path.resolve(__dirname, "dist")));
app.use(router.routes());

// router.get("/", async (ctx) => {
//   let content = await new Promise((resolve, reject) => {
//     render.renderToString((err, html) => {
//       resolve(html);
//     });
//   });
//   //   console.log("content---", content);
//   ctx.body = content;
// });

// koa-router 不能写成 * , 要写成正则
router.get("/(.*)", async (ctx) => {
  let content = await new Promise((resolve, reject) => {
    // render.renderToString 执行后就会调用服务端的入口文件方法
    // renderToString 的两个参数, 第一个传给 server 入口文件函数, 第二个参数是个函数, 其参数由入口文件传入，
    // 如果没有与路径匹配的组件就会得到 err , 此时 html 为 undefined
    // render.renderToString({ url: ctx.url }, (err, html) => {
    // ctx.url 即为前端请求的地址栏上路径，也可以视为组件名
    render.renderToString(ctx, (err, html) => {
      // console.log("html=========", html);
      if (err && err.code == 404) {
        return resolve("<h1>Not Found</h1>");
      }
      resolve(html);
    });
  });
  ctx.body = content;
});

app.listen(3000, () => {
  console.log(chalk.bold.red("app is running at port 3000"));
});
